package com.mes.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.OrderVo;
import com.mes.biz.service.*;
import com.mes.common.core.domain.model.LoginUser;
import com.mes.common.core.page.PageDomain;
import com.mes.common.exception.BizException;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.biz.mapper.BizOrderProductMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 销售单产品Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-05-15
 */
@Service
@Transactional(readOnly = true)
public class BizOrderProductServiceImpl extends BaseServiceImpl<BizOrderProductMapper, BizOrderProduct> implements BizOrderProductService {

    private static final Logger log = LoggerFactory.getLogger(BizOrderProductServiceImpl.class);

    @Resource
    private BizOrderProductMapper bizOrderProductMapper;
    @Resource
    private BizProcessUserService bizProcessUserService;
    @Resource
    private BizProductProcessPlanService bizProductProcessPlanService;
    @Resource
    private BizOrderProcessRecordService bizOrderProcessRecordService;
    @Resource
    private BizOrderService bizOrderService;
    @Resource
    private BizProductService bizProductService;

    /**
     * 获取单条数据
     * @param bizOrderProduct 销售单产品
     * @return 销售单产品
     */
    @Override
    public BizOrderProduct get(BizOrderProduct bizOrderProduct) {
        BizOrderProduct dto = super.get(bizOrderProduct);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 销售单产品id
     * @return 销售单产品
     */
    @Override
    public BizOrderProduct get(String id) {
        BizOrderProduct dto = super.get(id);
        return dto;
    }

    /**
     * 查询销售单产品列表
     * @param bizOrderProduct 销售单产品
     * @return 销售单产品
     */
    @Override
    public List<BizOrderProduct> findList(BizOrderProduct bizOrderProduct) {
		List<BizOrderProduct> bizOrderProductList = super.findList(bizOrderProduct);
        return bizOrderProductList;
    }

    /**
     * 分页查询销售单产品列表
     * @param bizOrderProduct 销售单产品
     * @return 销售单产品
     */
    @Override
    public PageInfo<BizOrderProduct> findPage(BizOrderProduct bizOrderProduct) {
		PageInfo<BizOrderProduct> page = super.findPage(bizOrderProduct);
        return page;
    }

    /**
     * 保存销售单产品
     * @param bizOrderProduct
     * @return 结果
     */
    @Override
    public boolean save(BizOrderProduct bizOrderProduct) {
        return super.save(bizOrderProduct);
    }

    /**
     * 删除销售单产品信息
     * @param bizOrderProduct
     * @return 结果
     */
    @Override
    public boolean remove(BizOrderProduct bizOrderProduct) {
        return super.remove(bizOrderProduct);
    }

    /**
     * 批量删除销售单产品
     * @param ids 需要删除的销售单产品ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizOrderProductByIds(String[] ids) {
        return mapper.deleteBizOrderProductByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public int deleteBizProductByOrderId(String orderId) {
        return mapper.deleteBizProductByOrderId(orderId, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public List<BizOrderProduct> getBizOrderProductByOrderId(String orderId) {
        return bizOrderProductMapper.getBizOrderProductByOrderId(orderId);
    }

    @Override
    public List<BizOrderProduct> detailList(String orderId) {
        List<BizOrderProduct> productList = bizOrderProductMapper.getProcessDetailList(orderId);
        if (productList != null && productList.size() > 0){
            for (BizOrderProduct product : productList){
                List<BizProductionProcess> productionProcessList = bizProductProcessPlanService.getCompletionByProductId(product.getProductId());
                product.setBizProductionProcessList(productionProcessList);
            }
        }
        return productList;
    }

//    @Override
//    public List<BizOrderProduct> getProcessDetailList(String orderId,String userId,String planId) {
//        List<BizOrderProduct> resList= new ArrayList<>();
//        List<BizOrderProduct> newList= new ArrayList<>();
//        Boolean flag =false;
//        List<BizOrderProduct> list= bizOrderProductMapper.getProcessDetailList(orderId);
//        if (list != null && list.size()>0){
//            List<BizProcessUser> bizProcessUserList = bizProcessUserService.getListByUserId(userId);
//            if (bizProcessUserList != null && bizProcessUserList.size()>0){
//                for (BizOrderProduct bizOrderProduct : list){
//                    List<String> productIdList = bizOrderProductMapper.getProcessIdByProductId(bizOrderProduct.getProductId(), orderId);
//                    if (productIdList !=null && productIdList.size()>0){
//                        for (BizProcessUser processUser:bizProcessUserList){
//                            for (String processId:productIdList){
//                                if (processUser.getProcessId().equals(processId)){
//                                    resList.add(bizOrderProduct);
//                                    flag=true;
//                                    break;
//                                }
//                            }
//                            if (flag){
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//        }
////        resList.forEach(i -> {
////            if (!newList.contains(i)) { // 如果新集合中不存在则插入
////                newList.add(i);
////            }
////        });
//        return resList;
//    }


    @Override
    public List<BizOrderProduct> getProcessDetailList(String orderId,String userId,String planId) {
        List<BizOrderProduct> resList= new ArrayList<>();
        List<BizOrderProduct> list= bizOrderProductMapper.getProcessDetailList(orderId);
        if (list != null && list.size() > 0) {
            for (BizOrderProduct bizOrderProduct : list) {
                List<String> productIdList = bizOrderProductMapper.getProcessIdByProductId(bizOrderProduct.getProductId(), orderId, bizOrderProduct.getId());
                if (productIdList != null && productIdList.size() > 0) {
                    resList.add(bizOrderProduct);

                }
            }
        }
        return resList;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean updateProcess(List<BizOrderProduct> bizOrderProductList) {
        if (bizOrderProductList != null && bizOrderProductList.size()>0){
            String orderId= bizOrderProductList.get(0).getOrderId();
            for (BizOrderProduct bizOrderProduct : bizOrderProductList) {
                List<BizOrderProcessRecord> recordList = bizOrderProduct.getRecordList();
                bizOrderProcessRecordService.deleteByOrderProductId(bizOrderProduct.getId());
                if (recordList != null && recordList.size()>0){
                    for (BizOrderProcessRecord processRecord : recordList){
                        if (StringUtils.isEmpty(processRecord.getProcessId())){
                            throw new BizException("工序id不能为空");
                        }
                        if (StringUtils.isEmpty(processRecord.getProcessPlanId())){
                            throw new BizException("工序计划id不能为空");
                        }
                        if (StringUtils.isEmpty(processRecord.getCompletedVol())){
                            processRecord.setCompletedVol("0");
                        }
                        processRecord.setTenantId(SecurityUtils.getTenantId());
                        processRecord.setId(null);
                        bizOrderProcessRecordService.save(processRecord);
                    }
                    BizOrderProcessRecord record=new BizOrderProcessRecord();
                    record.setOrderId(orderId);
                    record.setProductId(bizOrderProduct.getId());
                    record.setCompletedVol("0");
                    List<BizOrderProcessRecord> list = bizOrderProcessRecordService.findList(record);
                    if (list == null || list.size() <= 0) {
                        BizOrderProduct orderProduct = bizOrderProductMapper.get(bizOrderProduct.getId());
                        orderProduct.setOperationStatus("1");
                        bizOrderProductMapper.update(orderProduct);
                    }
                }
            }

            BizOrder bizOrder = bizOrderService.get(orderId);
            boolean orderStatus = true;
            List<BizOrderProduct> productList = bizOrderProductMapper.getNotInventoryByOrderId(orderId);
            if (productList != null && productList.size() > 0) {
                for (BizOrderProduct orderProduct : productList) {
                    if (StringUtils.isEmpty(orderProduct.getOperationStatus()) || "0".equals(orderProduct.getOperationStatus())) {
                        orderStatus = false;
                        break;
                    }
                }
            }else{
                orderStatus=false;
            }
            if (orderStatus) {
                if ("5".equals(bizOrder.getOrderStatus())) {
                    bizOrder.setOrderStatus("6");
                }
            }else {
                bizOrder.setOrderStatus("5");
            }
            bizOrderService.save(bizOrder);
        }
        return true;
    }

    @Override
    public PageInfo<BizOrderProduct> listOrderProduct(BizOrder bizOrder){
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<BizOrderProduct> bizOrderProducts = bizOrderProductMapper.listOrderProduct(bizOrder);
        for (BizOrderProduct bizOrderProduct : bizOrderProducts) {
            BizProduct bizProduct = bizProductService.get(bizOrderProduct.getProductId());
            bizOrderProduct.setBizProduct(bizProduct);
        }
        return new PageInfo(bizOrderProducts);
    }

    @Override
    public List<BizOrderProduct> getProductByOrderId(String orderId) {
        return mapper.getProductByOrderId(orderId);
    }
}
